package com.ray.service;

import static org.hamcrest.CoreMatchers.nullValue;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ray.bean.BomOrderBusinessListBean;
import com.ray.bean.BomOrderBusinessMaterialBean;
import com.ray.bean.BomOrderBusinessTitleBean;
import com.ray.bean.BomOrderLevelRank;
import com.ray.bean.BomOrderListBean;
import com.ray.bean.BomOrderMaterialBean;
import com.ray.bean.BomOrderTitleBean;
import com.ray.bean.BomToCreateOrderListBean;
import com.ray.bean.BomToCreateOrderMaterialBean;
import com.ray.bean.BomToCreateOrderTitleBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DhTotalDateBean;
import com.ray.bean.DifficultLevelRateBean;
import com.ray.bean.GlassMaterialBean;
import com.ray.bean.MyApplyForBomBean;
import com.ray.bean.OrderCustomTagBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.bean.TableColumnForBomOrderConfig;
import com.ray.bean.WasteRateBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.DingTalkMapper;
import com.ray.mapper.OrderCreateApplyMapper;
import com.ray.mapper.OrderCreateForBomOrderMapper;
import com.ray.mapper.OrderCreateMapper;
import com.ray.mapper.OrderInfoTemplateMapper;
/**
 * 
 * @author Shensg
 */
@Service
public class OrderCreateForBomOrderService {
	@Autowired
	OrderCreateForBomOrderMapper orderCreateForBomOrderMapper;
	@Autowired
	OrderCreateMapper orderCreateMapper;
	@Autowired
	OrderCreateApplyMapper orderCreateApplyMapper;
	@Autowired
	DingTalkMapper dingTalkMapper;
	@Autowired
	OrderCreateApplyService orderCreateApplyService;
	@Autowired
	OrderCreateMapper orderCreateMapperNoApply;
	@Autowired
	OrderInfoTemplateMapper orderInfoTemplateMapper;
	//损耗表列表
	public DatatablesViewPageBean<WasteRateBean> getWasteRateList(WasteRateBean wasteRateBean, Map map) {

		DatatablesViewPageBean<WasteRateBean> datatablesViewPageBean = new DatatablesViewPageBean<WasteRateBean>();
		
		List<WasteRateBean> wasteRateBeans = orderCreateForBomOrderMapper.getWasteRateData(wasteRateBean,map);
		int count = orderCreateForBomOrderMapper.getWasteRateCount(wasteRateBean,map);
	
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(wasteRateBeans);
		return datatablesViewPageBean;
	}

	public int saveWasteRate(WasteRateBean wasteRateBean, Map map) {
		// TODO Auto-generated method stub
		int i = orderCreateForBomOrderMapper.saveWasteRate(wasteRateBean,map);
		if(i==-1) {
			throw new ServiceException("订单数区间不能重叠");
		}
		return i;
	}
	
	public int saveWasteRateForBomSelf(List<WasteRateBean> wasteRateBeans, Map map) {
		// TODO Auto-generated method stub
		int i = orderCreateForBomOrderMapper.saveWasteRateForBomSelf(wasteRateBeans,map);
		return i;
	}

	public void updateWasteRate(WasteRateBean wasteRateBean, Map map) {
		// TODO Auto-generated method stub
		orderCreateForBomOrderMapper.updateWasteRate(wasteRateBean,map);
	}

	public WasteRateBean getWasteRateById(WasteRateBean wasteRateBean, Map map) {
		// TODO Auto-generated method stub
		WasteRateBean retwasteRateBean = orderCreateForBomOrderMapper.getWasteRateById(wasteRateBean,map);
		return retwasteRateBean;
	}

	public DatatablesViewPageBean<DifficultLevelRateBean> getDifficultLevelList(DifficultLevelRateBean difficultLevelBean, Map map) {
		// TODO Auto-generated method stub
		DatatablesViewPageBean<DifficultLevelRateBean> datatablesViewPageBean = new DatatablesViewPageBean<DifficultLevelRateBean>();
		
		List<DifficultLevelRateBean> difficultLevelRateBeans = orderCreateForBomOrderMapper.getDifficultLevelRateData(difficultLevelBean,map);
		int count = orderCreateForBomOrderMapper.getDifficultLevelRateCount(difficultLevelBean,map);
	
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(difficultLevelRateBeans);
		return datatablesViewPageBean;
	}

	public int saveDifficultLevelRate(DifficultLevelRateBean difficultLevelBean, Map map) {
		// TODO Auto-generated method stub
		int i = orderCreateForBomOrderMapper.saveDifficultLevelRate(difficultLevelBean,map);
		if(i==-1) {
			throw new ServiceException("难易度等级不能重复");
		}
		return i;
	}

	public void updateDifficultLevelRate(DifficultLevelRateBean difficultLevelBean, Map map) {
		// TODO Auto-generated method stub
		int i = orderCreateForBomOrderMapper.updateDifficultLevelRate(difficultLevelBean,map);
		if(i==-1) {
			throw new ServiceException("难易度等级不能重复");
		}
	}

	public DifficultLevelRateBean getDifficultLevelRateById(DifficultLevelRateBean difficultLevelBean, Map map) {
		// TODO Auto-generated method stub
		DifficultLevelRateBean retDifficultLevelRateBean = orderCreateForBomOrderMapper.getDifficultLevelRateById(difficultLevelBean,map);
		return retDifficultLevelRateBean;
	}

	public DatatablesViewPageBean<BomOrderTitleBean> getBomOrderTitleList(BomOrderTitleBean bomOrderTitleBean, Map map) {
		// TODO Auto-generated method stub
		DatatablesViewPageBean<BomOrderTitleBean> datatablesViewPageBean = new DatatablesViewPageBean<BomOrderTitleBean>();
		
		List<BomOrderTitleBean> bomOrderTitleBeans = orderCreateForBomOrderMapper.getBomOrderTitleListData(bomOrderTitleBean,map);
		int count = orderCreateForBomOrderMapper.getBomOrderTitleListCount(bomOrderTitleBean,map);
	
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(bomOrderTitleBeans);
		return datatablesViewPageBean;
	}

	public BomOrderTitleBean saveBomOrder(BomOrderListBean bean, Map map) {
		//保存bom订单抬头信息
		BomOrderTitleBean titleBean = bean.getTitleBean();
		//校验工厂型号是唯一 排除删除status = -2 的
		if(orderCreateForBomOrderMapper.hasFactoryNoCount(titleBean.getFactoryNo(),map)>0) {
			throw new ServiceException("工厂型号已存在,需要保证唯一!");
		}
		if(titleBean.getFactoryNo() ==null || "".equals(titleBean.getFactoryNo().trim())) {
			throw new ServiceException("工厂型号必填!");
		}
		//获取唯一标示 如果是更新则不需要
		if(bean.getTitleBean().getId()==null) {
			titleBean.setSerialNo(dingTalkMapper.getApprovalNo("BOM"));
		}else {
			//查询老的serialNo并赋值上去
			List<BomOrderTitleBean> bomOrderTitleBeans = orderCreateForBomOrderMapper.getBomOrderTitleListData(titleBean,map);
			if(bomOrderTitleBeans.size()<1) {
				throw new ServiceException(titleBean.getId() + " : 物料bom不存在" );
			}
			titleBean.setSerialNo(bomOrderTitleBeans.get(0).getSerialNo());
			// bom订单多人编辑不更新原来的创建人
			if(bomOrderTitleBeans.get(0).getCreater()!=null && bomOrderTitleBeans.get(0).getCreater()!=""){
				map.put("loginUserName" , bomOrderTitleBeans.get(0).getCreater());
			}
		}
		orderCreateForBomOrderMapper.saveBomOrderTitle(titleBean,map);
		int titleId = titleBean.getId();
		//循环按顺序保存bomorder中 如果有物料代码则补全物料信息
		List<BomOrderMaterialBean> bomOrderMaterialBeans = bean.getMaterialList();
		for (BomOrderMaterialBean bomOrderMaterialBean : bomOrderMaterialBeans) {
			bomOrderMaterialBean.setBomOrderTitleId(titleId);
			//判断物料代码是否存在 补全物料信息
			if(bomOrderMaterialBean.getMaterialCode()!=null && !"".equals(bomOrderMaterialBean.getMaterialCode().trim())) {
				fixMaterialInfo(bomOrderMaterialBean,map);
			}
		}
		//批量保存bom_order_detail
		/**
		 * 循环保存避免数据太多
		 */
		List<BomOrderMaterialBean> list_orderDetails_new= new ArrayList<>();
		for (int i = 0; i < bomOrderMaterialBeans.size(); i++) {
			list_orderDetails_new.add(bomOrderMaterialBeans.get(i));
			if(list_orderDetails_new.size()==20) {//每20条数据拆分
				orderCreateForBomOrderMapper.saveBomOrderDetailBatch(list_orderDetails_new);
				list_orderDetails_new.clear();
			}
		}
		if(list_orderDetails_new.size()>0) {//如果少于20条
			orderCreateForBomOrderMapper.saveBomOrderDetailBatch(list_orderDetails_new);
			list_orderDetails_new.clear();
		}
		
		BomOrderTitleBean retTitleBean = new BomOrderTitleBean();
		retTitleBean.setId(titleId);
		retTitleBean.setSerialNo(titleBean.getSerialNo());
		return retTitleBean;
	}
	
	public BomOrderTitleBean updateBomOrder(BomOrderListBean bean, Map map) {
		//判断是否已经审核
		if(orderCreateForBomOrderMapper.hasAuditById(bean.getTitleBean().getId())>0) {
			throw new ServiceException("该订单已审核,修改失败!");
		}
		//将老的titleId status设置成删除状态-2
		orderCreateForBomOrderMapper.updateBomOrderTitleStatus(-2,bean.getTitleBean().getId(),map);
		bean.getTitleBean().setStatus("-2");
		return saveBomOrder(bean,map);
	}
	
	public void updateBomOrderStatus(BomOrderTitleBean bomOrderTitleBean, Map map) {
		// TODO Auto-generated method stub
		if(Integer.valueOf(bomOrderTitleBean.getStatus()) == -2){
			// 查询是否有相同工厂型号的商务订单
			if(bomOrderTitleBean.getFactoryNo()==null || "".equals(bomOrderTitleBean.getFactoryNo())){
				throw new ServiceException("参数工厂型号不存在");
			}
			if(orderCreateForBomOrderMapper.hasBusinessSameFactory(bomOrderTitleBean.getFactoryNo() , map) != 0){
				throw new ServiceException("存在相同的工厂型号商务订单,无法删除");
			}
		}
		orderCreateForBomOrderMapper.updateBomOrderTitleStatus(Integer.valueOf(bomOrderTitleBean.getStatus()),bomOrderTitleBean.getId(),map);
	}
	
	

	public BomOrderListBean getBomOrderDetailById(BomOrderTitleBean bomOrderTitleBean, Map map) {
		// TODO Auto-generated method stub
		BomOrderListBean retBean = new BomOrderListBean();
		//通过id查询bom_order_title
		List<BomOrderTitleBean> bomOrderTitleBeans = orderCreateForBomOrderMapper.getBomOrderTitleListData(bomOrderTitleBean,map);
		if(bomOrderTitleBeans.size()<1) {
			//throw new ServiceException(bomOrderTitleBean.getId() + " : 物料bom不存在" );
			return null;
		}
		retBean.setTitleBean(bomOrderTitleBeans.get(0));
		//通过bom_order_title的id查询bom_order_detail
		List<BomOrderMaterialBean> bomOrderMaterialBeans = orderCreateForBomOrderMapper.getBomOrderDetailByTitleId(retBean.getTitleBean().getId(),bomOrderTitleBean.getDetailLineNo());
		retBean.setMaterialList(bomOrderMaterialBeans);
		return retBean;
	}
	

	public DatatablesViewPageBean<BomOrderBusinessTitleBean> getBomOrderBusinessList(BomOrderBusinessTitleBean bomOrderBusinessTitleBean, Map map) {
		DatatablesViewPageBean<BomOrderBusinessTitleBean> datatablesViewPageBean = new DatatablesViewPageBean<BomOrderBusinessTitleBean>();
		
		List<BomOrderBusinessTitleBean> bomOrderTitleBeans = orderCreateForBomOrderMapper.getBomOrderBusinessListData(bomOrderBusinessTitleBean,map);
		int count = orderCreateForBomOrderMapper.getBomOrderBusinessListCount(bomOrderBusinessTitleBean,map);
	
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(bomOrderTitleBeans);
		return datatablesViewPageBean;
	}

	public BomOrderBusinessTitleBean saveBomOrderBusiness(BomOrderBusinessListBean bean, Map map) {
		// TODO Auto-generated method stub
		//保存商务订单抬头信息
		BomOrderBusinessTitleBean titleBean = bean.getTitleBean();
		//校验订单编号是唯一 排除删除status = -2 的
		if(orderCreateForBomOrderMapper.hasOrderNoCountForBusiness(titleBean.getOrderNo(),map)>0) {
			throw new ServiceException("订单编号已存在,需要保证唯一!");
		}
		if(titleBean.getFactoryNo()==null || "".equals(titleBean.getFactoryNo().trim())) {
			throw new ServiceException("工厂型号必填!");
		}
		//获取唯一标示 如果是更新则不需要
		if(bean.getTitleBean().getId()==null) {
			titleBean.setSerialNo(dingTalkMapper.getApprovalNo("BOMBS"));
		}else {
			//查询老的serialNo并赋值上去
			List<BomOrderBusinessTitleBean> bomOrderBusinessTitleBeans = orderCreateForBomOrderMapper.getBomOrderBusinessListData(titleBean,map);
			if(bomOrderBusinessTitleBeans.size()<1) {
				throw new ServiceException(titleBean.getId() + " : 物料bom不存在" );
			}
			titleBean.setSerialNo(bomOrderBusinessTitleBeans.get(0).getSerialNo());
			// bom订单多人编辑不更新原来的创建人
			if(bomOrderBusinessTitleBeans.get(0).getCreater()!=null && bomOrderBusinessTitleBeans.get(0).getCreater()!=""){
				map.put("loginUserName" , bomOrderBusinessTitleBeans.get(0).getCreater());
			}
		}
		orderCreateForBomOrderMapper.saveBomOrderBusinessTitle(titleBean,map);
		int titleId = titleBean.getId();
		//循环按顺序保存bomorder中 如果有物料代码则补全物料信息
		List<BomOrderBusinessMaterialBean> bomOrderBusinessMaterialBeans = bean.getMaterialList();
		for (BomOrderBusinessMaterialBean businessMaterialBean : bomOrderBusinessMaterialBeans) {
			businessMaterialBean.setBusinessTitleId(titleId);
			//判断物料代码是否存在 补全物料信息
			if(businessMaterialBean.getMaterialCode()!=null && !"".equals(businessMaterialBean.getMaterialCode().trim())) {
				fixMaterialInfoForBusiness(businessMaterialBean,map);
			}
		}
		//批量保存bom_order_business_detail
		
		orderCreateForBomOrderMapper.saveBomOrderBusinessDetailBatch(bomOrderBusinessMaterialBeans);
		//保存镜片
		List<GlassMaterialBean> glassMaterialBeans = bean.getGlassMaterialBeans();
		for (GlassMaterialBean glassMaterialBean : glassMaterialBeans) {
			glassMaterialBean.setBusinessTitleId(titleId);
			if(glassMaterialBean.getMaterialCode()!=null && !"".equals(glassMaterialBean.getMaterialCode().trim())) {
				fixMaterialInfoForBusinessGlass(glassMaterialBean,map);
			}
		}
		//批量保存bom_order_business_glass
		orderCreateForBomOrderMapper.saveBomOrderBusinessGlassBatch(glassMaterialBeans);
		//保存大货交期
		List<DhTotalDateBean> dhTotalDateBeans = bean.getDhTotalDates();
		for (DhTotalDateBean dhTotalDateBean : dhTotalDateBeans) {
			dhTotalDateBean.setBusinessTitleId(titleId);
		}
		//批量保存bom_order_business_detail
		orderCreateForBomOrderMapper.saveBomOrderBusinessDhBatch(dhTotalDateBeans);
		
		BomOrderBusinessTitleBean retBusinessTitleBean = new BomOrderBusinessTitleBean();
		retBusinessTitleBean.setId(titleId);
		retBusinessTitleBean.setSerialNo(titleBean.getSerialNo());
		return retBusinessTitleBean;
	}

	
	//商务订单修改(未审核的时候)
	public BomOrderBusinessTitleBean updateBomOrderBusiness(BomOrderBusinessListBean bean, Map map) {
		//判断是否已经审核
		if(orderCreateForBomOrderMapper.hasAuditForBusinessById(bean.getTitleBean().getId())>0) {
			throw new ServiceException("该订单已审核,修改失败!");
		}
		//将老的titleId status设置成删除状态-2
		orderCreateForBomOrderMapper.updateBomOrderBusinessTitleStatus(-2,bean.getTitleBean(),map);
		BomOrderBusinessTitleBean retBusinessTitleBean = saveBomOrderBusiness(bean,map);
		return retBusinessTitleBean;
	}
	

	public void updateBomOrderBusinessStatus(BomOrderBusinessTitleBean bean, Map map) {
		if(Integer.valueOf(bean.getStatus()) == -2){
			// 查询是否有相同工厂型号的商务订单
			if(bean.getOrderNo()==null || "".equals(bean.getOrderNo())){
				throw new ServiceException("参数订单编号不存在");
			}
			if(orderCreateForBomOrderMapper.hasBusinessSameOrderNo(bean.getOrderNo() , map) != 0){
				throw new ServiceException("存在相同的订单编号的生产订单,无法删除");
			}
		}
		orderCreateForBomOrderMapper.updateBomOrderBusinessTitleStatus(Integer.valueOf(bean.getStatus()),bean,map);
	}
	
	public BomOrderBusinessListBean getBomOrderBusinessDetailById(BomOrderBusinessTitleBean bomOrderBusinessTitleBean, Map map) {
		// TODO Auto-generated method stub
		BomOrderBusinessListBean retBean = new BomOrderBusinessListBean();
		//通过id查询bom_order_business_title
		List<BomOrderBusinessTitleBean> bomOrderBusinessTitleBeans = orderCreateForBomOrderMapper.getBomOrderBusinessListData(bomOrderBusinessTitleBean,map);
		if(bomOrderBusinessTitleBeans.size()<1) {
			throw new ServiceException(bomOrderBusinessTitleBean.getId() + " : 商务订单不存在" );
		}
		retBean.setTitleBean(bomOrderBusinessTitleBeans.get(0));
		//通过bom_order_business_title的id查询bom_order_detail
		List<BomOrderBusinessMaterialBean> bomOrderBusinessMaterialBeans = orderCreateForBomOrderMapper.getBomOrderBusinessDetailByTitleId(bomOrderBusinessTitleBean.getId(),0);
		retBean.setMaterialList(bomOrderBusinessMaterialBeans);
		
		//通过bom_order_business_title的id查询glass
		List<GlassMaterialBean> glassMaterialBeans = orderCreateForBomOrderMapper.getBomOrderBusinessGlassByTitleId(bomOrderBusinessTitleBean.getId(),0);
		retBean.setGlassMaterialBeans(glassMaterialBeans);
		
		//通过bom_order_business_title的id查询dh
		List<DhTotalDateBean> dhTotalDateBeans = orderCreateForBomOrderMapper.getBomOrderBusinessDhByTitleId(bomOrderBusinessTitleBean.getId(),0);
		retBean.setDhTotalDates(dhTotalDateBeans);
		return retBean;
	}
	
	public void updateSystemTableConfigForBomOrder(Map map) {
		// TODO Auto-generated method stub
		orderCreateForBomOrderMapper.updateSystemTableConfigForBomOrder(map);
	}
	
	public void updateSystemTableConfigForBomOrderForApply(Map map) {
		// TODO Auto-generated method stub
		orderCreateForBomOrderMapper.updateSystemTableConfigForBomOrderForApply(map);
	}
	
	public TableColumnForBomOrderConfig getSystemTableConfigForBomOrder(Map map) {
		// TODO Auto-generated method stub
		return orderCreateForBomOrderMapper.getSystemTableConfigForBomOrder(map);
	}
	public TableColumnForBomOrderConfig getSystemTableConfigForBomOrderForApply(Map map) {
		// TODO Auto-generated method stub
		return orderCreateForBomOrderMapper.getSystemTableConfigForBomOrderForApply(map);
	}
	
	

	public BomOrderTitleBean saveBomOrderForApply(BomOrderListBean bean, Map map) {
		
		//获取ApplyId
		String applyId = dingTalkMapper.getApprovalNo("Apply");
		//保存bom订单抬头信息
		BomOrderTitleBean titleBean = bean.getTitleBean();
		titleBean.setApplyId(applyId);
		// 订单申请修改避免订单原本制单人更换
		if(titleBean.getCreater()!=null && titleBean.getCreater()!=""){
			map.put("loginUserName" , titleBean.getCreater());
		}
		orderCreateForBomOrderMapper.saveBomOrderTitleForApply(titleBean,map);
		int titleId = titleBean.getId();
		//循环按顺序保存bomorder中 如果有物料代码则补全物料信息
		List<BomOrderMaterialBean> bomOrderMaterialBeans = bean.getMaterialList();
		for (BomOrderMaterialBean bomOrderMaterialBean : bomOrderMaterialBeans) {
			bomOrderMaterialBean.setBomOrderTitleId(titleId);
			//判断物料代码是否存在 补全物料信息
			if(bomOrderMaterialBean.getMaterialCode()!=null && !"".equals(bomOrderMaterialBean.getMaterialCode().trim())) {
				fixMaterialInfo(bomOrderMaterialBean,map);
			}
		}
		//批量保存bom_order_detail
		/**
		 * 循环 避免数据太多
		 */
		List<BomOrderMaterialBean> list_orderDetails_new= new ArrayList<>();
		for (int i = 0; i < bomOrderMaterialBeans.size(); i++) {
			list_orderDetails_new.add(bomOrderMaterialBeans.get(i));
			if(list_orderDetails_new.size()==20) {//每20条数据拆分
				orderCreateForBomOrderMapper.saveBomOrderDetailBatchForApply(list_orderDetails_new);
				list_orderDetails_new.clear();
			}
		}
		if(list_orderDetails_new.size()>0) {//如果少于20条
			orderCreateForBomOrderMapper.saveBomOrderDetailBatchForApply(list_orderDetails_new);
			list_orderDetails_new.clear();
		}
		//保存到my_apply_for_bom
		orderCreateForBomOrderMapper.saveMyApplyForBom(titleBean,map);
		sendMsg();
		
		BomOrderTitleBean retTitleBean = new BomOrderTitleBean();
		retTitleBean.setId(titleId);
		retTitleBean.setApplyId(applyId);
		retTitleBean.setSerialNo(titleBean.getSerialNo());
		return retTitleBean;
	}

	//通过物料代码补全物料信息
	public  void fixMaterialInfo(BomOrderMaterialBean bean, Map requestMap) {
			OrderInfoDetailBean beanByCode = orderCreateMapper.getMaterialInfoByCode(bean.getMaterialCode(),requestMap);
			if(beanByCode!=null) {
				bean.setMaterialModel(beanByCode.getMaterialModel());//规格
				bean.setMaterialName(beanByCode.getMaterialName());//物料名称
				bean.setMaterialProviderName(beanByCode.getProviderName());//供应商
				bean.setMaterialColor(beanByCode.getColor());//色号
			}
	}
	public  void fixMaterialInfoForBusiness(BomOrderBusinessMaterialBean bean, Map requestMap) {
		OrderInfoDetailBean beanByCode = orderCreateMapper.getMaterialInfoByCode(bean.getMaterialCode(),requestMap);
		if(beanByCode!=null) {
			bean.setMaterialModel(beanByCode.getMaterialModel());//规格
			bean.setMaterialName(beanByCode.getMaterialName());//物料名称
			bean.setMaterialProviderName(beanByCode.getProviderName());//供应商
			bean.setMaterialColor(beanByCode.getColor());//色号
		}
	}

	private void fixMaterialInfoForBusinessGlass(GlassMaterialBean bean, Map requestMap) {
		// TODO Auto-generated method stub
		OrderInfoDetailBean beanByCode = orderCreateMapper.getMaterialInfoByCode(bean.getMaterialCode(),requestMap);
		if(beanByCode!=null) {
			bean.setMaterialModel(beanByCode.getMaterialModel());//规格
			bean.setMaterialName(beanByCode.getMaterialName());//物料名称
			bean.setMaterialProviderName(beanByCode.getProviderName());//供应商
			bean.setMaterialColor(beanByCode.getColor());//色号
		}
	}

	public BomOrderListBean getBomOrderByApplyIdForApply(BomOrderTitleBean bomOrderTitleBean, Map map) {
		// TODO Auto-generated method stub
		BomOrderListBean retBean = new BomOrderListBean();
		//通过id查询bom_order_title
		List<BomOrderTitleBean> bomOrderTitleBeans = orderCreateForBomOrderMapper.getBomOrderTitleListDataForApply(bomOrderTitleBean,map);
		if(bomOrderTitleBeans.size()<1) {
			throw new ServiceException(bomOrderTitleBean.getApplyId() + " : 物料bom不存在" );
		}
		retBean.setTitleBean(bomOrderTitleBeans.get(0));
		//通过bom_order_title的applyId查询bom_order_detail
		List<BomOrderMaterialBean> bomOrderMaterialBeans = orderCreateForBomOrderMapper.getBomOrderDetailByTitleIdForApply(retBean.getTitleBean().getId(),bomOrderTitleBean.getDetailLineNo());
		retBean.setMaterialList(bomOrderMaterialBeans);
		return retBean;
	}
	/**
	 * type = 1  bomOrder
	 * @param applyBean
	 * @param map
	 */
	public void updateBomOrderForApply(MyApplyForBomBean bean, Map map) {
		//判断是否审核 -1待审核 1成功 0 退回
		MyApplyForBomBean applyBean = orderCreateForBomOrderMapper.getMyApplyForBom(bean,map);
		if(applyBean.getStatus() != -1) {
			throw new ServiceException("订单已审核");
		}
		if(applyBean.getSerialNo() == null || "".equals(applyBean.getSerialNo())) {
			throw new ServiceException("serialNo 参数不存在");
		}
		applyBean.setStatus(bean.getStatus());
		//判断审核状态
		if (bean.getStatus() == 0 ) {
			//退回 审核不通过
			orderCreateForBomOrderMapper.updateMyApplyForBomStatus(bean,map);
			//写入my_audit_for_bom
			orderCreateForBomOrderMapper.saveMyAuditForApply(applyBean,map);
			return;
		}
		if(bean.getStatus() == 1) {
			//审核通过
			//更新apply 写入audit
			orderCreateForBomOrderMapper.updateMyApplyForBomStatus(bean,map);
			//写入my_audit_for_bom
			orderCreateForBomOrderMapper.saveMyAuditForApply(applyBean,map);
			
			//如果审核通过 数据从元数据到audit
			BomOrderTitleBean beanForOne = new BomOrderTitleBean();
			orderCreateForBomOrderMapper.saveBomOrderTitleToAudit(bean,beanForOne,map);
			orderCreateForBomOrderMapper.saveBomOrderDetailToAudit(bean,beanForOne.getId(),map);
			//将元数据状态数据删除
			orderCreateForBomOrderMapper.updateBomOrderTitleStatusBySerialNo(-2, bean.getSerialNo(), map);
			//apply到元数据
			BomOrderTitleBean beanForTwo = new BomOrderTitleBean();
			orderCreateForBomOrderMapper.saveBomOrderTitleFromApply(bean,beanForTwo,map);
			orderCreateForBomOrderMapper.saveBomOrderDetailFromApply(bean,beanForTwo.getId(),map);
			//如果审核通过 配置表从apply到元配置表
			orderCreateForBomOrderMapper.saveSystemTableConfigFromApply(bean,applyBean.getSerialNo(),map);
			//如果审核通过 wate_rate 损耗表 apply中新增一份过来
			orderCreateForBomOrderMapper.saveWastRateFromApply(bean,applyBean.getSerialNo(),map);
			//TD 如果审核通过 通知所有相同工厂型号并且状态不是-2（删除）的商务订单 的制单人
			sendMsg();
		}
		
	}
	
	public List<WasteRateBean> getWasteRateForBomSelf(WasteRateBean wasteRateBean, Map map) {
		// TODO Auto-generated method stub
		return orderCreateForBomOrderMapper.getWasteRateForBomSelf(wasteRateBean, map);
	}
	
	

	public BomOrderBusinessTitleBean saveBomOrderBusinessApply(BomOrderBusinessListBean bean,Map map) {
		// TODO Auto-generated method stub
		//保存商务订单抬头信息
		BomOrderBusinessTitleBean titleBean = bean.getTitleBean();
		//校验订单编号是唯一 排除删除status = -2 的
		
		if(titleBean.getFactoryNo()==null || "".equals(titleBean.getFactoryNo().trim())) {
			throw new ServiceException("工厂型号必填!");
		}

		String applyId = dingTalkMapper.getApprovalNo("Apply");
		titleBean.setApplyId(applyId);
		
		//获取唯一标示 如果是更新则不需要
		/*if(bean.getTitleBean().getId()==null) {
			titleBean.setSerialNo(dingTalkMapper.getApprovalNo("BOMBS"));
		}else {
			//查询老的serialNo并赋值上去
			List<BomOrderBusinessTitleBean> bomOrderBusinessTitleBeans = orderCreateForBomOrderMapper.getBomOrderBusinessListData(titleBean,map);
			if(bomOrderBusinessTitleBeans.size()<1) {
				throw new ServiceException(titleBean.getId() + " : 物料bom不存在" );
			}
			titleBean.setSerialNo(bomOrderBusinessTitleBeans.get(0).getSerialNo());
		}*/
		// 订单申请修改避免订单原本制单人更换
		if(titleBean.getCreater()!=null && titleBean.getCreater()!=""){
			map.put("loginUserName" , titleBean.getCreater());
		}
		orderCreateForBomOrderMapper.saveBomOrderBusinessTitleApply(titleBean,map);
		int titleId = titleBean.getId();
		//循环按顺序保存bomorder中 如果有物料代码则补全物料信息
		List<BomOrderBusinessMaterialBean> bomOrderBusinessMaterialBeans = bean.getMaterialList();
		for (BomOrderBusinessMaterialBean businessMaterialBean : bomOrderBusinessMaterialBeans) {
			businessMaterialBean.setBusinessTitleId(titleId);
			//判断物料代码是否存在 补全物料信息
			if(businessMaterialBean.getMaterialCode()!=null && !"".equals(businessMaterialBean.getMaterialCode().trim())) {
				fixMaterialInfoForBusiness(businessMaterialBean,map);
			}
		}
		//批量保存bom_order_business_detail
		
		orderCreateForBomOrderMapper.saveBomOrderBusinessDetailBatchApply(bomOrderBusinessMaterialBeans);
		//保存镜片
		List<GlassMaterialBean> glassMaterialBeans = bean.getGlassMaterialBeans();
		for (GlassMaterialBean glassMaterialBean : glassMaterialBeans) {
			glassMaterialBean.setBusinessTitleId(titleId);
			if(glassMaterialBean.getMaterialCode()!=null && !"".equals(glassMaterialBean.getMaterialCode().trim())) {
				fixMaterialInfoForBusinessGlass(glassMaterialBean,map);
			}
		}
		//批量保存bom_order_business_glass
		orderCreateForBomOrderMapper.saveBomOrderBusinessGlassBatchApply(glassMaterialBeans);
		//保存大货交期
		List<DhTotalDateBean> dhTotalDateBeans = bean.getDhTotalDates();
		for (DhTotalDateBean dhTotalDateBean : dhTotalDateBeans) {
			dhTotalDateBean.setBusinessTitleId(titleId);
		}
		//批量保存bom_order_business_detail
		orderCreateForBomOrderMapper.saveBomOrderBusinessDhBatchApply(dhTotalDateBeans);
		
		//保存到my_apply_for_bom
		orderCreateForBomOrderMapper.saveMyApplyForBomBusiness(titleBean,map);
		sendMsg();
		
		BomOrderBusinessTitleBean retBusinessTitleBean = new BomOrderBusinessTitleBean();
		retBusinessTitleBean.setId(titleId);
		retBusinessTitleBean.setSerialNo(titleBean.getSerialNo());
		retBusinessTitleBean.setApplyId(applyId);
		return retBusinessTitleBean;
	}
	
	public void sendMsg() {
		
	}

	public BomOrderBusinessListBean getBomOrderBusinessDetailByIdForApply(BomOrderBusinessTitleBean bomOrderBusinessTitleBean, Map map) {
		// TODO Auto-generated method stub
		if(bomOrderBusinessTitleBean.getApplyId() == null) {
			throw new ServiceException("Apply参数不存在" );
		}
		BomOrderBusinessListBean retBean = new BomOrderBusinessListBean();
		//通过id查询bom_order_business_title
		List<BomOrderBusinessTitleBean> bomOrderBusinessTitleBeans = orderCreateForBomOrderMapper.getBomOrderBusinessListDataApply(bomOrderBusinessTitleBean,map);
		if(bomOrderBusinessTitleBeans.size()<1) {
			return null ;
		}
		retBean.setTitleBean(bomOrderBusinessTitleBeans.get(0));
		//通过bom_order_business_title的id查询bom_order_detail
		List<BomOrderBusinessMaterialBean> bomOrderBusinessMaterialBeans = orderCreateForBomOrderMapper.getBomOrderBusinessDetailByTitleIdForApply(retBean.getTitleBean().getId(),0);
		retBean.setMaterialList(bomOrderBusinessMaterialBeans);
		
		//通过bom_order_business_title的id查询glass
		List<GlassMaterialBean> glassMaterialBeans = orderCreateForBomOrderMapper.getBomOrderBusinessGlassByTitleIdForApply(retBean.getTitleBean().getId(),0);
		retBean.setGlassMaterialBeans(glassMaterialBeans);
		
		//通过bom_order_business_title的id查询dh
		List<DhTotalDateBean> dhTotalDateBeans = orderCreateForBomOrderMapper.getBomOrderBusinessDhByTitleIdForApply(retBean.getTitleBean().getId(),0);
		retBean.setDhTotalDates(dhTotalDateBeans);
		return retBean;
	}
	
	
	/**
	 * type = 2  bomOrder
	 * @param applyBean
	 * @param map
	 */
	public void updateBomOrderBussinessForApply(MyApplyForBomBean bean, Map map) {
		//判断是否审核 -1待审核 1成功 0 退回
		MyApplyForBomBean applyBean = orderCreateForBomOrderMapper.getMyApplyForBom(bean,map);
		if(applyBean.getStatus() != -1) {
			throw new ServiceException("订单已审核");
		}
		if(applyBean.getSerialNo() == null || "".equals(applyBean.getSerialNo())) {
			throw new ServiceException("serialNo 参数不存在");
		}
		applyBean.setStatus(bean.getStatus());
		//判断审核状态
		if (bean.getStatus() == 0 ) {
			//退回 审核不通过
			orderCreateForBomOrderMapper.updateMyApplyForBomStatus(bean,map);
			//写入my_audit_for_bom
			orderCreateForBomOrderMapper.saveMyAuditForApply(applyBean,map);
			return;
		}
		if(bean.getStatus() == 1) {
			//审核通过
			//更新apply 写入audit
			orderCreateForBomOrderMapper.updateMyApplyForBomStatus(bean,map);
			//写入my_audit_for_bom
			orderCreateForBomOrderMapper.saveMyAuditForApply(applyBean,map);
			
			//如果审核通过 数据从元数据到audit
			BomOrderBusinessTitleBean beanForOne = new BomOrderBusinessTitleBean();
			//title
			orderCreateForBomOrderMapper.saveBomOrderBusinessTitleToAudit(bean,beanForOne,map);
			//detail
			orderCreateForBomOrderMapper.saveBomOrderBusinessDetailToAudit(bean,beanForOne.getId(),map);
			//glass
			orderCreateForBomOrderMapper.saveBomOrderBusinessGlassToAudit(bean,beanForOne.getId(),map);
			//dh交期
			orderCreateForBomOrderMapper.saveBomOrderBusinessDhToAudit(bean,beanForOne.getId(),map);
			
			//将元数据状态数据删除
			BomOrderBusinessTitleBean updateBomOrderBuisinessBean = new BomOrderBusinessTitleBean();
			updateBomOrderBuisinessBean.setSerialNo(applyBean.getSerialNo());
			orderCreateForBomOrderMapper.updateBomOrderBusinessTitleStatus(-2,updateBomOrderBuisinessBean,map);
			
			//apply到元数据 title
			BomOrderBusinessTitleBean beanForTwo = new BomOrderBusinessTitleBean();
			orderCreateForBomOrderMapper.saveBomOrderBusinessTitleFromApply(bean,beanForTwo,map);
			//detail
			orderCreateForBomOrderMapper.saveBomOrderBusinessDetailFromApply(bean,beanForTwo.getId(),map);
			//glass
			orderCreateForBomOrderMapper.saveBomOrderBusinessGlassFromApply(bean,beanForTwo.getId(),map);
			//dh交期
			orderCreateForBomOrderMapper.saveBomOrderBusinessDhFromApply(bean,beanForTwo.getId(),map);
			
			//如果审核通过 配置表从apply到元配置表
			orderCreateForBomOrderMapper.saveSystemTableConfigFromApply(bean,applyBean.getSerialNo(),map);
			
			//TD 如果审核通过 通知所有相同工厂型号并且状态不是-2（删除）的商务订单 的制单人
			sendMsg();
		}
		
	}

	public DatatablesViewPageBean<BomOrderLevelRank> getLevelRankList(BomOrderLevelRank bean, Map map) {
		DatatablesViewPageBean<BomOrderLevelRank> datatablesViewPageBean = new DatatablesViewPageBean<BomOrderLevelRank>();
		
		List<BomOrderLevelRank> bomOrderLevelRanks = orderCreateForBomOrderMapper.getBomOrderLevelRankData(bean,map);
		int count = orderCreateForBomOrderMapper.getBomOrderLevelRankCount(bean,map);
	
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(bomOrderLevelRanks);
		return datatablesViewPageBean;
	}

	public void updateLevelRank(BomOrderLevelRank bean, Map map) {
		// TODO Auto-generated method stub
		orderCreateForBomOrderMapper.updateLevelRank(bean,map);
	}

	public void saveLevelRank(BomOrderLevelRank bean, Map map) {
		// TODO Auto-generated method stub
		orderCreateForBomOrderMapper.saveLevelRank(bean,map);
	}

	public void saveOrderByBomOrder(BomToCreateOrderListBean bomToCreateOrderListBean,Map map) {
		// TODO Auto-generated method stub
		
		
		BomToCreateOrderTitleBean titleBean = bomToCreateOrderListBean.getTitleBean();
		List<BomToCreateOrderMaterialBean> materialBeans = bomToCreateOrderListBean.getMaterialBeans();
		String orderTemplateId = bomToCreateOrderListBean.getOrderTemplateId();
		
		String action = map.get("action").toString();//add 新增 update修改
		//判断订单编号是否已经存在
		map.put("name", "order_p_order_no_comp");
		map.put("value", titleBean.getOrderNo());
		List<Map> retMap  = orderCreateMapper.getOrderInfoByParam(map);
		if(retMap.size()!=0 && "add".equals(action)) {//如果新增的时候需要判断
			//存在则删除原先订单模板并返回错误
			map.put("id", orderTemplateId);
			map.put("status", 0);
			orderInfoTemplateMapper.updateTemplateById(map);
			throw new ServiceException("订单编号："+titleBean.getOrderNo()+"已存在,请保证唯一");
		}
		
		
		//删除原有订单信息 生产订单主表, order_info_detail order_info_tail order_custom_tag
		int id = orderCreateMapper.deleteOrderInfo(titleBean.getSysOrderNo());
		
		orderCreateForBomOrderMapper.saveOrderTitleByBomOrder(titleBean,map);
		List<BomToCreateOrderMaterialBean> list_orderDetails_new= new ArrayList<>();
		for (int i = 0; i < materialBeans.size(); i++) {
			list_orderDetails_new.add(materialBeans.get(i));
			if(list_orderDetails_new.size()==20) {//每20条数据拆分
				orderCreateForBomOrderMapper.saveOrderMaterialByBomOrder(list_orderDetails_new,titleBean.getSysOrderNo(),map);
				list_orderDetails_new.clear();
			}
		}
		if(list_orderDetails_new.size()>0) {//如果少于20条
			orderCreateForBomOrderMapper.saveOrderMaterialByBomOrder(list_orderDetails_new,titleBean.getSysOrderNo(),map);
			list_orderDetails_new.clear();
		}
		//保存模板
		if(Integer.valueOf(orderTemplateId)!=0) {
			orderCreateMapper.deleteOrderInfoAndTemplate(titleBean.getSysOrderNo());
			int id_order_template = orderCreateMapper.saveOrderInfoAndTemplate(titleBean.getSysOrderNo(),orderTemplateId);
		}
		map.put("order_no", titleBean.getOrderNo());
		map.put("order_p_product_no", titleBean.getFactoryNo());
		map.put("status", "");
		orderCreateApplyService.sendTemplateMsg("apply",map);
	}
	
	public BomToCreateOrderListBean getOrderBySysOrderNo(String sysOrderNo,Map map) {
		BomToCreateOrderListBean retBean = new BomToCreateOrderListBean();
		BomToCreateOrderTitleBean titleBean = orderCreateForBomOrderMapper.getOrderTitleBySysOrder(sysOrderNo,map);
		List<BomToCreateOrderMaterialBean> materialBeans = orderCreateForBomOrderMapper.getOrderMaterialBySysOrder(sysOrderNo,map);
		retBean.setTitleBean(titleBean);
		retBean.setMaterialBeans(materialBeans);
		retBean.setOrderTemplateId(orderCreateForBomOrderMapper.getTemplateIdBySysOrderNo(sysOrderNo));
		return retBean;
	}
	/**
	 * 申请修改保存订单信息
	 * @param map
	 * @return
	 */
	public boolean saveOrderInfoForApply(BomToCreateOrderListBean bomToCreateOrderListBean,Map<String, Object> map) {
		BomToCreateOrderTitleBean titleBean = bomToCreateOrderListBean.getTitleBean();
		List<BomToCreateOrderMaterialBean> materialBeans = bomToCreateOrderListBean.getMaterialBeans();
		String order_no = titleBean.getSysOrderNo();
		map.put("order_p_order_no",order_no);
		
		/*校验是否有申请中的数据*/
		List<Map<String, String>> listMyApply = orderCreateMapperNoApply.getMyApplyInfo(order_no);
		if(listMyApply.size()>0) {
			throw new ServiceException("订单已经申请,请勿重复提交\r\n" +
    		  		"申请人["+listMyApply.get(0).get("apply_user")+"] 申请时间["+listMyApply.get(0).get("apply_time")+"]");
		}
		String orderTemplateId = bomToCreateOrderListBean.getOrderTemplateId();
		int id_primary = orderCreateForBomOrderMapper.saveOrderInfoForApply(titleBean,map);
		List<BomToCreateOrderMaterialBean> list_orderDetails_new= new ArrayList<>();
		for (int i = 0; i < materialBeans.size(); i++) {
			list_orderDetails_new.add(materialBeans.get(i));
			if(list_orderDetails_new.size()==20) {//每20条数据拆分
				orderCreateForBomOrderMapper.saveOrderInfoDetailForApply(list_orderDetails_new,order_no,map,titleBean.getApplyId());
				list_orderDetails_new.clear();
			}
		}
		if(list_orderDetails_new.size()>0) {//如果少于20条
			orderCreateForBomOrderMapper.saveOrderInfoDetailForApply(list_orderDetails_new,order_no,map,titleBean.getApplyId());
			list_orderDetails_new.clear();
		}
		//保存模板
		if(Integer.valueOf(orderTemplateId)!=0) {
			int id_order_template = orderCreateApplyMapper.saveOrderInfoAndTemplate(titleBean.getSysOrderNo(),orderTemplateId,titleBean.getApplyId());
		}
		return true;
	}
	
	public BomToCreateOrderListBean getApplyOrder(String sysOrderNo,String applyId ,Map map) {
		BomToCreateOrderListBean retBean = new BomToCreateOrderListBean();
		BomToCreateOrderTitleBean titleBean = orderCreateForBomOrderMapper.getOrderTitleApply(sysOrderNo,applyId,map);
		List<BomToCreateOrderMaterialBean> materialBeans = orderCreateForBomOrderMapper.getOrderMaterialApply(sysOrderNo,applyId,map);
		retBean.setTitleBean(titleBean);
		retBean.setMaterialBeans(materialBeans);
		retBean.setOrderTemplateId(orderCreateForBomOrderMapper.getTemplateIdApply(sysOrderNo,applyId));
		return retBean;
	}

	public Object getBomInfoForOpen(Map<String, Object> params) {
		String companyId = null;
		String lineNo = null;
		String factoryNo = null;
		if(params.get("companyId") == null) {
			throw new ServiceException("companyId 公司Id参数为空");
		}
		companyId = params.get("companyId").toString();
		if(params.get("lineNo") == null) {
			throw new ServiceException("lineNo 行号参数为空");
		}
		lineNo = params.get("lineNo").toString();
		if(params.get("factoryNo") == null) {
			throw new ServiceException("factoryNo 工厂型号参数为空");
		}
		factoryNo = params.get("factoryNo").toString();
		
		Map retMap = orderCreateForBomOrderMapper.getBomInfoForOpen(companyId,lineNo,factoryNo);
		
		return retMap;
	}

	
	
	
	
}
